package com.luo.config;

import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.luo.utils.JwtUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;


@Component
public class JWTInterceptor implements HandlerInterceptor {
    public static  Map<String, Object> map;
    //查看状态
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
         map = new HashMap<>();

        // 解决跨域问题，所有options请求统统放行
        if ("OPTIONS".equals(request.getMethod().toUpperCase())) {
            return true;
        }

        // 获取请求头中的token
        String token = request.getHeader("token");
        if(token!=null){
            System.out.println("token-->"+token);
        }
        if(token!=null){
            try {
                JwtUtil.verify(token);
                return true;
            }  catch (AlgorithmMismatchException e) {
                //e.printStackTrace();
                map.put("code",10013);
                map.put("msg", "token算法不一致");
            } catch (Exception e) {
                //e.printStackTrace();
                map.put("code",10011);
                map.put("msg", "token无效");
            }
        }else{
            map.put("code",10009);
            map.put("msg", "无token"); // 设置状态
        }
        return true;
    }
}
